package com.yc.navy.springmvc.util;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

public class WaterMarkUtil {
	private static final String FONT_NAME = "微软雅黑";
	private static final int FONT_SIZE = 20;
	private static final int FONT_STYLE = Font.BOLD;
	private static final Color FONT_COLOR = Color.red;
	private static final String MRAK_TEXT = "信息";
	
	/**
	 * 给指定的图片加文字水印
	 */
	public static void textWaterMark(File f1) {
		FileOutputStream fos = null;
		
		try {
			Image image = ImageIO.read(f1);	//读取图片文件
			
			//获取图片大小，以便在右下角添加水印
			int width = image.getWidth(null);
			int height = image.getHeight(null);
			
			//创建一个图片缓冲区
			BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			
			//获取这个缓冲区的绘画工具
			Graphics2D gp = bufferedImage.createGraphics();
			
			//先将原有的图片数据绘制进去
			gp.drawImage(image, 0, 0, width, height, null);
			
			//绘制水印
			gp.setFont(new Font(FONT_NAME, FONT_STYLE, FONT_SIZE));
			
			//设置文本的颜色
			gp.setColor(FONT_COLOR);
			
			//计算文本的大小
			int textWidth = FONT_SIZE * getTextLength(MRAK_TEXT);
			int textHeight = FONT_SIZE;
			
			//设置透明度
			gp.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.8F));
			
			int x = width - textWidth - 10;
			int y = height - textHeight + 5;
			
			//在指定位置绘制字符串
			gp.drawString(MRAK_TEXT, x, y);
			
			//释放工具
			gp.dispose();
			
			//将这个缓冲区数据写到到源文件
			fos = new FileOutputStream(f1.getAbsoluteFile());
			ImageIO.write(bufferedImage, "JPEG", fos);
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private static int getTextLength(String text) {
		int length = text.length();
		String temp;
		for(int i = 0, len = length; i < len; ++i) {
			temp = String.valueOf(text.charAt(i));
			if(temp.getBytes().length > 1) {
				++length;
			}
		}
		length = length % 2 == 0 ? length / 2 : length / 2 + 1 ;
		return length;
	}
	
	public static void main(String[] args) {
		textWaterMark(new File("slide02.jpg"));
	}
}
